package backtrack;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 93. 复原 IP 地址
 * User: Li_yizYa
 * Date: 2025/6/17
 * Time: 14:57
 */
public class Solution7 {
    public List<String> restoreIpAddresses(String s) {
        List<String> ret = new ArrayList<>();
        if (s == null || s.length() == 0) {
            return ret;
        }
        StringBuilder str = new StringBuilder(s);
        backTracking(ret, str, 0, 0);
        return ret;
    }

    private void backTracking(List<String> ret, StringBuilder str, int dotCount, int index) {
        if (dotCount == 3) {
            if (isValid(str, index, str.length() - 1)) {
                ret.add(str.toString());
            }
            return;
        }
        for (int i = index; i < str.length(); i++) {
            if (isValid(str, index, i)) {
                str.insert(i + 1, ".");
                backTracking(ret, str, dotCount + 1, i + 2);
                str.deleteCharAt(i + 1);
            } else {
                return;
            }
        }
    }

    private boolean isValid(StringBuilder str, int left, int right) {
        if (left > right) {
            return false;
        }
        if (str.charAt(left) == '0' && left != right) {
            return false;
        }
        int num = 0;
        for (int i = left; i <= right; i++) {
            int digit = str.charAt(i) - '0';
            num = num * 10 + digit;
            if (num > 255) {
                return false;
            }
        }
        return true;
    }
}
